package com.fita.tencent.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.fita.entity.user.UserSource;
import com.fita.entity.user.WechatAccount;
import com.fita.entity.user.WechatOpenid;
import com.fita.tencent.dao.WechatAccountDao;
import com.fita.tencent.entity.weappauth.WeappAuth;
import com.fita.tencent.service.WeappAuthService;

/**
 * 
 * @author mohanlan
 *
 */
@Service("weappAuthService")
public class WeappAuthServiceImpl implements WeappAuthService {
    
    @Dao
    private WechatAccountDao wechatAccountDao;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /*
     * (non-Javadoc)
     * @see com.fita.tencent.service.WeappAuthService#authorize(java.lang.String, com.fita.tencent.entity.weappauth.WeappAuth, com.fita.entity.user.UserSource)
     */
    public WechatAccount authorize(String sessionKey, WeappAuth weappAuth, UserSource source) {
        
        String unionid = weappAuth.getUnionid();
        
        // 1. load wechat account
        WechatAccount account = wechatAccountDao.getWechatAccountByUnionid(unionid);
        
        if(account == null) {
        	account = new WechatAccount(source, sessionKey, weappAuth.getUnionid(), weappAuth.getNickName(), weappAuth.getGender(), weappAuth.getCountry(), weappAuth.getProvince(), weappAuth.getAvatar());
            genericDaoSupport.save(account);
        } else {
            genericDaoSupport.update(account.refresh(sessionKey, weappAuth.getNickName(), weappAuth.getGender(), weappAuth.getCountry(), weappAuth.getProvince(), weappAuth.getAvatar()));
        }
        
        WechatOpenid wechatOpenid = wechatAccountDao.getWechatOpenid(unionid, UserSource.FITA_WEAPP_ACCOUNT);
        
        if(wechatOpenid == null) {
          wechatOpenid = new WechatOpenid(weappAuth.getOpenid(), unionid, UserSource.FITA_WEAPP_ACCOUNT);
          genericDaoSupport.save(wechatOpenid);
        } 
        
        return account;
    }
}
